var util = require("../../utils/util.js");
//获取全局APP里的URL
var app = getApp();
Page({
  data: {
    movies:{},
    requestUrl:{},
    dataCount:0,
    isMoviesNull:true
  },
  onLoad: function (options) {
    var categorys = options.categorys;
    this.setData({
      categorys: categorys
    });

    var publicUrl = app.globalData.doubanBase;
    var dataUrl = "";

    switch (categorys) {
      case "正在热映":
        dataUrl = publicUrl + "/v2/movie/in_theaters";
        break;
      case "即将上映":
        dataUrl = publicUrl + "/v2/movie/coming_soon";
        break;
      case "排行榜":
        dataUrl = publicUrl + "/v2/movie/top250";
        break;
    }
    this.setData({
      dataUrl:dataUrl
    })
    wx.showNavigationBarLoading();
    util.http(dataUrl, this.callback);
  },
  callback:function(res){
    var movies = [];
      for (var idx in res.subjects) {
        var subject = res.subjects[idx];
        var title = subject.title;
        if (title.length >= 6) {
          title = title.substring(0, 6) + "...";
        }
        //处理评星
        var temp = {
          stars: util.convertToStarsArray(subject.rating.stars),
          title: title,
          average: subject.rating.average,
          coverageUrl: subject.images.large,
          movieId: subject.id
        }
        movies.push(temp);
      }
      //存储合并之后的数据
      var allMovies = {};
      var dataCountAdd = this.data.dataCount += 20;
      if(!this.data.isMoviesNull){
        //合并老的数据
        allMovies = this.data.movies.concat(movies);
      }else{
        this.setData({
          isMoviesNull:false
        })
        allMovies = movies;
      }
      this.setData({
        //在这里记得初始化movies
        movies: allMovies,
        //处理数据请求的累加
        dataCount:dataCountAdd
      })
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
  },

  //设置动态导航
  onReady: function () {
    wx.setNavigationBarTitle({
      title: this.data.categorys
    })
  },

  //下拉加载
  onPullDownRefresh:function(event){
    var refreshURL = this.data.dataUrl+"?start=0&count=20";
    this.setData({
      movies:{},
      isMoviesNull:true
    })
    util.http(refreshURL, this.callback);
    wx.showNavigationBarLoading();
  },

  //上滑加载
  onReachBottom:function(event){
    var nextUrl = this.data.dataUrl+"?start="+this.data.dataCount+"&count=20";
    util.http(nextUrl, this.callback);
    wx.showNavigationBarLoading();
  },

  //跳转到详情
  onMovieDetailTap: function (event) {
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: '../movies-detail/movies-detail?movieid='+movieId
    })
  }

})